﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using FANUC.DTO;
using Newtonsoft.Json;
using System.Web.Http.Description;
using AutoMapper;

namespace FANUC.Controllers
{
    public class RobotParametersMaintainController : ApiController
    {
        private FANUCDB db = new FANUCDB();

        [ResponseType(typeof(ParameterVersionsListDtoOutput))]
        public IHttpActionResult Get()
        {
            var parameterVersions = db.Parameter_Version.ToList();
            if (parameterVersions.Count <= 0)
            {
                return NotFound();
            }
            var config = new MapperConfiguration(cfg => {
                cfg.CreateMap<Parameter_Version, ParameterVersionDto>().ForMember(dest => dest.Robot_YH_No, src => src.MapFrom(s => s.Robot.YH_No));
                cfg.CreateMap<Parameter_Value, ParameterValueDto>();
            });
            //config.AssertConfigurationIsValid();
            var mapper = config.CreateMapper();

            List<ParameterVersionDto> parameterVersionList = mapper.Map<List<Parameter_Version>,List<ParameterVersionDto>>(parameterVersions);
            ParameterVersionsListDtoOutput data = new ParameterVersionsListDtoOutput();
            data.ParameterVersionsDto = parameterVersionList;

            return Ok(data);
        }

        /// <summary>
        /// Get: api/ApiRobotParameter/?id=Robot_YH_No&version_no=1
        /// </summary>
        /// <param name="id">Robot_YH_No</param>
        /// /// <param name="version_no">Version_No</param>
        /// <returns>ParameterVersionListDtoOutput</returns>
        [ResponseType(typeof(ParameterVersionDto))]
        public IHttpActionResult Get(string id, int version_no)
        {
            var parameterVersion = db.Parameter_Version.Where(a => a.Robot.YH_No == id && a.Version_No == version_no).FirstOrDefault();
            if (parameterVersion == null)
            {
                return NotFound();
            }
            AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Parameter_Version, ParameterVersionDto>().ForMember(dest => dest.Robot_YH_No, src => src.MapFrom(s => s.Robot.YH_No)));
            AutoMapper.Mapper.Initialize(cfg => cfg.CreateMap<Parameter_Value, ParameterValueDto>());

            ParameterVersionDto parameterVersionDto = AutoMapper.Mapper.Map<ParameterVersionDto>(parameterVersion);

            return Ok(parameterVersionDto);
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        public string Options()
        { return null; }
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
